package util;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.logging.log4j.core.appender.AppenderLoggingException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class TokenHelper {
    //签名
    public static final String SING = "XG201902104014";

    public static String getToken(String username) {
        //创建JWT对象
        JWTCreator.Builder builder = JWT.create();
        //创建Calendar对象
        Calendar instance = Calendar.getInstance();
        //设置过期时间为7天
        instance.add(Calendar.DATE, 7);
        String token = builder.withClaim("name",username)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));
        return token;
    }

    public static Collection<String> verify(String token, HttpServletResponse response) throws IOException {
        JSONObject message = new JSONObject();
        Collection<String> collections = new LinkedList<>();
        try {
            //创建验证对象
            DecodedJWT verify =
                    JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
            //解码对象
            collections.add(verify.getClaim("name").asString());
            collections.add(verify.getExpiresAt().toString());
        }
        catch (SignatureVerificationException e) {
            message.put("message", "签名不一致");
            response.getWriter().println(message);
        }
        catch (TokenExpiredException e) {
            message.put("message", "令牌过期");
            response.getWriter().println(message);
        }
        catch (AlgorithmMismatchException e) {
            message.put("message", "算法不匹配");
            response.getWriter().println(message);
        }
        catch (InvalidClaimException e) {
            message.put("message", "失效的payload");
            response.getWriter().println(message);
        }
        catch (Exception e) {
            message.put("message", "没有权限");
            response.getWriter().println(message);
        }

        return collections;
    }
}

